﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

namespace Dazaza.Framework.Data
{
    public class DataConnection
    {
        /// <summary>
        /// 根据 config/connectionConfig.config配置，获取name=参数的SqlDatabase对象
        /// </summary>
        /// <param name="connectionName"></param>
        /// <returns></returns>
        public static SqlDatabase GetConnection(string connectionName)
        {
            string connectionString=string.Empty;

            //读取配置
            Config.ConnectionConfig connectionConfig = Config.ConfigManager.GetConnectionConfig();

            //寻找所有 Name = connectionName 的配置项
            List<Config.ConnectionConfigItem> connectionConfigItems = connectionConfig.ConnectionConfigItems
                .Where(x=>string.Equals(x.Name,connectionName, StringComparison.OrdinalIgnoreCase))
                .ToList();

            if (connectionConfigItems == null)
            {
                throw new Exception(string.Format("没有找到配置名为{0}的配置项", connectionName));
            }
            else
            {
                if (connectionConfigItems.Count() == 1)
                {
                    connectionString = connectionConfigItems[0].ConnectionString;
                }
                else
                {
                    //如果发现多个同名配置项，则随机选取
                    Random r = new Random(Guid.NewGuid().GetHashCode());
                    var rndnum = r.Next(connectionConfigItems.Count-1);
                    connectionString = connectionConfigItems[rndnum].ConnectionString;
                }
            }

            return new SqlDatabase(connectionString);
        }
    }
}
